﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace Web.Ajax.Export
{
	public class Csv
	{
		public static string ConvertField(string val)
		{
			if (val != null)
				val=val.Replace("\"", "\"\"");
			return "\"" + val + "\"";
		}

		public static string ExportToCsv(DataTable dt, params string[] cols)
		{
			if (cols == null)
			{
				var colslist = new List<string>();
				foreach (DataColumn c in dt.Columns)
				{
					colslist.Add(c.ColumnName);
				}
				cols = colslist.ToArray();
			}
			var first = true;
			StringBuilder csv = new StringBuilder();
			foreach (string col in cols)
			{
				if (!first)
					csv.Append(",");
				first = false;
				csv.Append(ConvertField(col));
			}
			csv.Append("\r\n");
			foreach (DataRow row in dt.Rows)
			{
				first = true;
				foreach (string col in cols)
				{
					if (!first)
						csv.Append(",");
					first = false;
					csv.Append(ConvertField(row[col].ToString()));
				}
				csv.Append("\r\n");
			}
			return csv.ToString();
		}
	}
}
